package client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.KeyStore;
import java.util.Scanner;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class Client {
	public static void main(String[] args) throws Exception {
		SSLSocket socket = null;

		if (args.length < 3) {
			System.out.println("Gör så här:");
			System.out
					.println("java [executable] [keystore file] [keystore pass] [private pass]");
			System.exit(1);
		}

		String keystoreFile = args[0];
		char[] keystorePass = args[1].toCharArray();
		char[] certPass = args[2].toCharArray();
		System.setProperty("javax.net.ssl.trustStore", args[0]);
		System.setProperty("javax.net.ssl.trustStorePassword", args[1]);

		try {
			KeyStore keyStore = KeyStore.getInstance("JKS");
			System.out.println(keystoreFile + " " + keystorePass.toString());
			keyStore.load(new FileInputStream(keystoreFile), keystorePass);
			KeyManagerFactory keyManagerFactory = KeyManagerFactory
					.getInstance("SunX509");
			keyManagerFactory.init(keyStore, certPass);
			SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
			SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
			socket = (SSLSocket) sslSocketFactory.createSocket("localhost",
					8889);
			socket.startHandshake();

		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("client error: " + e.toString());
			System.exit(1);
		}

		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				socket.getOutputStream()));
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				socket.getInputStream()));

		Scanner scanner = new Scanner(System.in);
		String command;
		while (true) {
			System.out.print(">> ");
			command = scanner.nextLine().trim();

			if (command.equals("EXIT")) {
				socket.close();
				System.exit(0);
			} else {
				writer.write(command + ";\n");
				writer.flush();
				char buff = 0;
				while ((buff = (char) reader.read()) != '\0') {
					System.out.print((char) buff);
				}
			}
		}
	}
}
